package com.ycy.temperature;

import android.Manifest;
import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.util.Log;
import android.widget.Toast;

import com.google.gson.Gson;
import com.jude.utils.JUtils;
import com.ycy.temperature.bean.CityBean;
import com.ycy.temperature.date.utils.SharedPreferencesUtils;
import com.ycy.temperature.view.activity.LoginActivity;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;

/**
 * Created by MI on 2018/7/18.
 */

public class App extends Application implements Application.ActivityLifecycleCallbacks {
    private static App INSTANCE;
    ArrayList<Activity> activitiesCollected = new ArrayList<>();
    public String StrCity = "";

    @Override
    public void onCreate() {
        super.onCreate();
        INSTANCE = this;
        //初始化JUtils工具类
        JUtils.initialize(this);
        //初始化数据存储方法
        SharedPreferencesUtils.init(this);
        //获取当前位置
        getLocation();
//初始化Application.ActivityLifecycleCallbacks
        registerActivityLifecycleCallbacks(this);
    }

    public static App getInstance() {
        return INSTANCE;
    }

    public void exitApp() {
        for (Activity activity : activitiesCollected) {
            if (null != activity && !activity.isFinishing()) {
                activity.finish();
                Log.e("activitiesCollected", "activitiesCollected");
            }
        }
        activitiesCollected.clear();
        Intent intent3 = new Intent(this, LoginActivity.class);
        startActivity(intent3);

    }

    @Override
    public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
    }

    @Override
    public void onActivityStarted(Activity activity) {
        activitiesCollected.add(activity);
    }

    @Override
    public void onActivityResumed(Activity activity) {
    }

    @Override
    public void onActivityPaused(Activity activity) {
    }

    @Override
    public void onActivityStopped(Activity activity) {
    }

    @Override
    public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
    }

    @Override
    public void onActivityDestroyed(Activity activity) {
    }

    public void getLocation() {
        String locationProvider;
        //获取地理位置管理器
        LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        //获取所有可用的位置提供器
        List<String> providers = locationManager.getProviders(true);
        if (providers.contains(LocationManager.GPS_PROVIDER)) {
            //如果是GPS
            locationProvider = LocationManager.GPS_PROVIDER;
        } else if (providers.contains(LocationManager.NETWORK_PROVIDER)) {
            //如果是Network
            locationProvider = LocationManager.NETWORK_PROVIDER;
        } else {
            Toast.makeText(this, "没有可用的位置提供器", Toast.LENGTH_SHORT).show();
            return;
        }
        //获取Location
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            return;
        }
        Location location = locationManager.getLastKnownLocation(locationProvider);
        if (location != null) {
            //不为空,显示地理位置经纬度
            showLocation(location);
        }
        //监视地理位置变化
        locationManager.requestLocationUpdates(locationProvider, 3000, 1, locationListener);
    }

    /**
     * 显示地理位置经度和纬度信息
     *
     * @param location
     */
    private void showLocation(Location location) {
        String locationStr = "纬度：" + location.getLatitude() + "\n"
                + "经度：" + location.getLongitude();
        updateVersion(location.getLatitude() + "", location.getLongitude() + "");
    }

    /**
     * LocationListern监听器
     * 参数：地理位置提供器、监听位置变化的时间间隔、位置变化的距离间隔、LocationListener监听器
     */

    LocationListener locationListener = new LocationListener() {

        @Override
        public void onLocationChanged(Location location) {
            showLocation(location);
        }

        @Override
        public void onStatusChanged(String provider, int status, Bundle arg2) {

        }

        @Override
        public void onProviderEnabled(String provider) {

        }

        @Override
        public void onProviderDisabled(String provider) {

        }

    };

    public void updateVersion(String wd, String jd) {
        String path = "http://api.map.baidu.com/geocoder?output=json&location=" + wd + "," + jd + "&key=oyLW65unagFzNVLp39E7EV356tg7QOdZ";
        OkHttpUtils
                .get()
                .url(path)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call arg0, Exception arg1, int arg2) {
                    }

                    @Override
                    public void onResponse(String arg0, int arg1) {
                        Gson gson = new Gson();
                        CityBean response = gson.fromJson(arg0, CityBean.class);
                        if (response.getStatus().equals("OK")) {
                            StrCity = response.getResult().getAddressComponent().getProvince();
                        }
                    }
                });
    }

}
